
const stripe = base.getStripeObject()

document.addEventListener('click', event => {
    makeProductPayment(event);
    addProductToCart(event);
    closeStandardNotification(event);
    makePaymentToShoppingCart(event);
})


function makePaymentToShoppingCart(event) {
    // Выполняем оплату корзины продуктов

    if (!event.target.closest('[data-buy-shopping-cart]')) return;
    event.preventDefault();

    const token = document.querySelector(
        '.buy-shopping-cart-form>input[name="csrfmiddlewaretoken"]'
    ).value;
    const url = document.location.origin + '/cart/?pay_for_order=true';
    const body = {'token': token}
    base.sendAjaxRequest('POST', url, body)
        .then(result => {
            const checkoutSessionId = result.checkout_session_id;
            return stripe.redirectToCheckout({ sessionId: checkoutSessionId });
        })
}

function closeStandardNotification(event) {
    // Закрываем стандартное оповещение

    if (!event.target.closest('[data-close-standard-notification]')) return;
    document.querySelector('.standard-notification').remove();
}


function makeProductPayment(event) {
    // Выполняем оплату продукта

    if (!event.target.closest('[data-buy-product]')) return;
    event.preventDefault();

    const [token, product_id] = base.get_basic_information_about_single_product()
    const url = document.location.origin + `/buy/${product_id}/?session_to_pay_for_product=true`;
    const body = {'token': token}
    base.sendAjaxRequest('POST', url, body)
        .then(result => {
            insertPaymentForm();
            return result.client_secret
        })
        .then(client_secret => {
            const options = {
                clientSecret: client_secret
            };
            const elements = stripe.elements(options);
            const paymentElement = elements.create('payment');
            paymentElement.mount('#payment-element');
        })

    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ


    function insertPaymentForm() {
        // Вставляем форму оплаты

        const paymentForm = base.getPaymentForm();
        const content = document.querySelector('.content');
        content.innerHTML = '';
        content.insertAdjacentElement(
            'beforeend',
            paymentForm
        );
    }
}


function addProductToCart(event) {
    // Добавляем продукт в корзину

    if (!event.target.closest('[data-add-product-to-cart]')) return;
    event.preventDefault();

    const [token, product_id] = base.get_basic_information_about_single_product();
    const url = document.location.origin + '/cart/?add_product_to_cart=true';
    const body = {'token': token, 'product_id': product_id};
    base.sendAjaxRequest('POST', url, body)
        .then(result => {
            base.showNotification(result.message);
        })
}
